//
//  LBOverlayColor.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 3/29/13.
//  Copyright (c) 2013 UIT. All rights reserved.
//

#include "LBOverlayColorFilter.h"
#include "LBGraphics.h"

char fShaderStrOverlayColor[] = ""
"precision mediump float;"

"varying vec2 vtexCoor;"
"varying vec4 vposition;"
"uniform sampler2D texture;"
"uniform vec4 color;"
"uniform float opacity;"


// overlay function
"vec4 overlay(vec4 base, vec4 overlay, float opacity){"

"   mediump float ra;"
"    if (2.0 * base.r < base.a) {"
"        ra = 2.0 * overlay.r * base.r + overlay.r * (1.0 - base.a) + base.r * (1.0 - overlay.a);"
"    } else {"
"        ra = overlay.a * base.a - 2.0 * (base.a - base.r) * (overlay.a - overlay.r) + overlay.r * (1.0 - base.a) + base.r * (1.0 - overlay.a);"
"    }"

"    mediump float ga;"
"    if (2.0 * base.g < base.a) {"
"        ga = 2.0 * overlay.g * base.g + overlay.g * (1.0 - base.a) + base.g * (1.0 - overlay.a);"
"    } else {"
"        ga = overlay.a * base.a - 2.0 * (base.a - base.g) * (overlay.a - overlay.g) + overlay.g * (1.0 - base.a) + base.g * (1.0 - overlay.a);"
"    }"

"    mediump float ba;"
"    if (2.0 * base.b < base.a) {"
"        ba = 2.0 * overlay.b * base.b + overlay.b * (1.0 - base.a) + base.b * (1.0 - overlay.a);"
"    } else {"
"        ba = overlay.a * base.a - 2.0 * (base.a - base.b) * (overlay.a - overlay.b) + overlay.b * (1.0 - base.a) + base.b * (1.0 - overlay.a);"
"    }"

"    vec4 result = vec4(ra, ga, ba, 1.0);"
"   result = mix(base, result, opacity);"
"   return result;"
"}"
// END overlay function


"void main()"
"{"
"    lowp vec4 textureColor = texture2D(texture, vtexCoor);"
"    textureColor = overlay(textureColor, color, opacity);"
"    gl_FragColor = textureColor;"
"}";

LBOverlayColorFilter::LBOverlayColorFilter(){
    init(0, fShaderStrOverlayColor);
    LBGraphics::getInstance()->useProgram(program);
    colorUniform = program->uniformIndex("color");
    opacityUniform = program->uniformIndex("opacity");
    setColor(1.0f, 1.0f, 1.0f);
    setOpactiy(1.0f);
}